<?php
//---------------------------------------------------------
//               Buddha Bless, No Bug !
//         User: wuxuehai Date: 2018/7/31 Time: 下午3:40
//---------------------------------------------------------

namespace common\models;

use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;

/**
 *
 * @property-read mixed $statusName
 * @property-read array|string[] $statusOptions
 */
class BaseModel extends ActiveRecord
{
    const STATUS_INACTIVE = 0;
    const STATUS_ACTIVE = 1;

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
            ],
        ];
    }

    /**
     * @return array
     */
    public function getStatusOptions()
    {
        return [
            self::STATUS_INACTIVE => '关闭',
            self::STATUS_ACTIVE => '启用',
        ];
    }

    /**
     * @return mixed
     */
    public function getStatusName()
    {
        $item = $this->statusOptions;
        return ArrayHelper::getValue($item, $this->status, '无');
    }


    /**
     * 获取总条数
     * @param array $where
     * @return int|string
     */
    public static function count(array $where = [])
    {
        return static::find()->where($where)->count();
    }

    /**
     * 获取option列表
     * @param array $where
     * @param string $from
     * @param string $to
     * @return array
     */
    public static function getListForOptions($where = ['status' => self::STATUS_ACTIVE], $from = 'id', $to = 'title')
    {
        $list = static::findAll($where);
        return ArrayHelper::map($list, $from, $to);
    }

    /**
     * 根据ID获取字段值
     * @param $id
     * @param $field
     * @return mixed|string
     */
    public static function getFieldById($id, $field)
    {
        $info = static::find()->where(['id' => $id])->one();
        return ArrayHelper::getValue($info, $field);
    }

    public static function getAutoCacheDependencyKey()
    {
        return static::CACHE_PREFIX . \Yii::$app->db->schema->getRawTableName(static::tableName());
    }
}
